package com.yuer.tools.myfileziptools.service.impl;


import com.yuer.tools.myfileziptools.constant.LagouUrlPathInft;
import com.yuer.tools.myfileziptools.pojo.dto.ExcelStudyOut;
import com.yuer.tools.myfileziptools.pojo.dto.LagouExcelStudyDetailOut;
import com.yuer.tools.myfileziptools.pojo.dto.LagouStudentInfoDetailDto;
import com.yuer.tools.myfileziptools.pojo.dto.LagouStudentStudyCourseInfoDto;
import com.yuer.tools.myfileziptools.response.CommonResponse;
import com.yuer.tools.myfileziptools.response.CommonResponseFactory;
import com.yuer.tools.myfileziptools.service.LagouStudentDetailServer;
import com.yuer.tools.myfileziptools.utils.BigDecimalUtils;
import com.yuer.tools.myfileziptools.utils.ExcelUtil;
import com.yuer.tools.myfileziptools.utils.PinYinUtil;
import com.yuer.tools.myfileziptools.utils.exception.ExceptionProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class LagouStudentDetailServerImpl implements LagouStudentDetailServer {

    @Autowired(required = false)
    private RestTemplate restTemplate;
    private final String [] bigCourseDescript = {
            "Java工程师高薪训练营",
            "Java就业急训营",
            "数据分析实战训练营",
            "大数据开发高薪训练营",
            "大前端就业急训营",
            "大厂offer私教计划",
            "AI人工智能训练营",
            "PMP考前突击营",
    };

    @Override
    public void parseExportSutdentDetailRate(HttpServletResponse httpServletResponse,String cookie,Integer courseId,Integer classId,Integer conditionPersonNum) {
        CommonResponse  commonResponse = parseSutdentDetailRate(cookie,courseId,classId,conditionPersonNum);
        if(commonResponse.getCode().equals("SUCCESS")){
            ExcelStudyOut excelStudyOut  = (ExcelStudyOut) commonResponse.getData();
            List<LagouExcelStudyDetailOut> lagouExcelStudyDetailOutList  = excelStudyOut.getLagouExcelStudyDetailOutList();

            ExcelUtil excelUtil = new ExcelUtil();
            String colName = "序号,学生姓名,报课内容,报课数量,完成率";
            String columnFieldStr = "index,studentName,joinCourseContent,joinCount";
            try {
                excelUtil.exportExcelNew( "class_count_detail"/*excelStudyOut.getCurrentClassProidDetail()+"学情统计情况"*/,excelStudyOut.getSumUp(), colName, columnFieldStr, lagouExcelStudyDetailOutList, httpServletResponse);
            } catch (Exception e) {
                log.error("com.yuer.tools.myfileziptools.service.imple.LagouStudentDetailServerImpl.parseSutdentDetailRate::Exception ::[{}]",e);
                e.printStackTrace();
            }

        }

    }

    @Override
    public CommonResponse parseSutdentDetailRate(String cookie, Integer courseId, Integer classId, Integer conditionPersonNum) {
        CommonResponse  response = null;
//        int pageNo = 0;
        try {
            List<LagouStudentInfoDetailDto> studentList = new ArrayList<>();
            for (int pageNpo = 1 ; pageNpo< 5; pageNpo++){ // 学生班级多的话 5页数据
                MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
                HttpHeaders headers = new HttpHeaders();
                headers.add("Cookie",cookie);
                String url = String.format(LagouUrlPathInft.STUDENT_LIST_URL,courseId,classId,pageNpo);
                HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity(map, headers);

                headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
                HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
                ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

                JSONObject jsonObject = new JSONObject(responseEntity.getBody());
                int code = jsonObject.optInt("state", 0);
                if (code != 1) {
                    return CommonResponseFactory.getInstance().error("失败");
                }
                String content = jsonObject.optString("content");
                JSONArray recordListArray = new JSONObject(content).optJSONArray("recordList");
                if(recordListArray == null || recordListArray.length() ==0){
                   break;
                }
                for (int i =0; i < recordListArray.length(); i++){
                    String  studentName = recordListArray.optJSONObject(i).optString("studentName");
                    String  className = recordListArray.optJSONObject(i).optString("className");
                    LagouStudentInfoDetailDto lagouStudentInfoDetailDto = new LagouStudentInfoDetailDto();
                    lagouStudentInfoDetailDto.setStudentName(studentName);
                    lagouStudentInfoDetailDto.setClassName(className);
                    studentList.add(lagouStudentInfoDetailDto);
                }
            }
            String currentClassName = studentList.get(0).getClassName();

//            Class type = new LagouStudentInfoDetailDto().getClass();
//            Type type2 =new TypeToken<List<LagouStudentInfoDetailDto>>(){}.getType();
//            Gson gson = new Gson();
//            LagouStudentInfoDetailDto [] list  = gson.fromJson(recordListArray.toString(), type2);
//            List<LagouStudentInfoDetailDto> studentList =    Arrays.asList(list);

            int countJoinStuNum = 0;
            int totleStuNum = studentList.size();
            LinkedList<String> resultOs = new LinkedList<>();
           /* for (LagouStudentInfoDetailDto infoDetailDto:studentList) {
                List<LagouStudentStudyCourseInfoDto> detailDtoList =  parseCourse(cookie,infoDetailDto.getStudentName());
                if(detailDtoList.size() >= conditionPersonNum){
                    countJoinStuNum++;
                }
                StringBuilder sb = new StringBuilder();
                sb.append("姓名：").append(infoDetailDto.getStudentName()).append(" ").append("已报课：");
                for (int i =0 ; i< detailDtoList.size();i++){
                    int index = i +1;
                    LagouStudentStudyCourseInfoDto studyCourseInfoDto = detailDtoList.get(i);
                    sb.append(index+"、").append(studyCourseInfoDto.getCourseName()).append(" ");
                }
                resultOs.add(sb.toString());
            }

            double joinRate =BigDecimalUtils.setDifScare( BigDecimalUtils.divide(countJoinStuNum+"", ""+ totleStuNum).doubleValue());
//            String joinRate = BigDecimalUtils.setFenScare(BigDecimalUtils.divide(countJoinStuNum+"", ""+ totleStuNum));
            String message = String.format("%s共有%d名学生，已复购人数：%d，未复购人数：%d,复购率:%f",studentList.get(0).getClassName(),totleStuNum,countJoinStuNum,totleStuNum - countJoinStuNum ,joinRate);
            resultOs.addFirst("具体报课如下：");
            resultOs.addFirst(message);*/
            List<String> bigCourseDescriptList = Arrays.asList(bigCourseDescript);
            //整理成excel格式的model
            List<LagouExcelStudyDetailOut> lagouExcelStudyDetailOutList = new ArrayList<>();
            int indexCount = 1;
            for (LagouStudentInfoDetailDto infoDetailDto:studentList) {
                List<LagouStudentStudyCourseInfoDto> detailDtoList =  parseCourse(cookie,infoDetailDto.getStudentName());
                /*if(detailDtoList.size() >= conditionPersonNum){
                    countJoinStuNum++;
                }*/
                StringBuilder sb = new StringBuilder();
                sb.append("已报课：");
                LagouExcelStudyDetailOut lagouExcelStudyDetailOut = new LagouExcelStudyDetailOut();
                for (int i =0 ; i< detailDtoList.size();i++){
                    LagouStudentStudyCourseInfoDto studyCourseInfoDto = detailDtoList.get(i);
                    if(currentClassName.contains(studyCourseInfoDto.getCourseName())){
                        System.out.println("匹配当前的班级成功");
                        bigCourseDescriptList.remove(currentClassName);
                        break;
                    }
                }
                int currentStudentJoinCount = 0;
                for (int i =0 ; i< detailDtoList.size();i++){
                    LagouStudentStudyCourseInfoDto studyCourseInfoDto = detailDtoList.get(i);
                    for (String s:bigCourseDescriptList){
                        if(studyCourseInfoDto.getCourseName().contains(s)){
                            currentStudentJoinCount++;
                            System.out.println("匹配到复购了大课");
                            int index = i +1;
                            sb.append(index+"、").append(studyCourseInfoDto.getCourseName()).append(" ");
                        }
                    }
                }

                if(currentStudentJoinCount > 1){
                    countJoinStuNum++;
                    lagouExcelStudyDetailOut.setIsJsoin(1);
                }
                lagouExcelStudyDetailOut.setIsJsoin(1);
                lagouExcelStudyDetailOut.setIndex(indexCount++);
                lagouExcelStudyDetailOut.setStudentName(infoDetailDto.getStudentName());
                lagouExcelStudyDetailOut.setJoinCount(currentStudentJoinCount);
                lagouExcelStudyDetailOut.setJoinCourseContent(sb.toString());
                lagouExcelStudyDetailOut.setCompleteRate("");
                lagouExcelStudyDetailOutList.add(lagouExcelStudyDetailOut);
//                resultOs.add(sb.toString());
            }
            double joinRate =BigDecimalUtils.setDifScare( BigDecimalUtils.divide(countJoinStuNum+"", ""+ totleStuNum).doubleValue());
            String message = String.format("%s共有%d名学生，已复购人数：%d，未复购人数：%d,复购率:%f",currentClassName,totleStuNum,countJoinStuNum,totleStuNum - countJoinStuNum ,joinRate);
            ExcelStudyOut excelStudyOut = new ExcelStudyOut();
            excelStudyOut.setSumUp(message);
            excelStudyOut.setCurrentClassProidDetail(studentList.get(0).getClassName());
            excelStudyOut.setLagouExcelStudyDetailOutList(lagouExcelStudyDetailOutList);
            response = CommonResponseFactory.getInstance().success(excelStudyOut);
        } catch (JSONException e) {
            log.error("com.yuer.tools.myfileziptools.service.imple.LagouStudentDetailServerImpl.parseSutdentDetailRate::Exception ::[{}]",e);
            response=CommonResponseFactory.getInstance().error("失败");
            ExceptionProcessUtils.wrapperHandlerException(response,e);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return response;
    }

    private List<LagouStudentStudyCourseInfoDto> parseCourse(String Cookie,String name){
        List<LagouStudentStudyCourseInfoDto> studentStudyCourseDtoList = new ArrayList<>();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie",Cookie);
        String url = String.format(LagouUrlPathInft.STUDENT_STUDY_COURSE_LIST_URL,name);
//        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity(map, headers);
//        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, param, String.class);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        try {
            JSONObject jsonObject = new JSONObject(responseEntity.getBody());
            int code = jsonObject.optInt("state", 0);
            if (code != 1) {
                return null;
            }
            String content = jsonObject.optString("content");
            String bigCourseStudentDTOPage = new JSONObject(content).optString("bigCourseStudentDTOPage");
            JSONArray recordListArray = new JSONObject(bigCourseStudentDTOPage).optJSONArray("recordList");
            //List<LagouStudentStudyCourseInfoDto> studentStudyCourseDtoList = JsonUtil.StringTolist(recordList, LagouStudentStudyCourseInfoDto.class);
            for (int i =0; i < recordListArray.length(); i++){
                String  courseName = recordListArray.optJSONObject(i).optString("courseName");
                String  stuName = recordListArray.optJSONObject(i).optString("studentName");
                LagouStudentStudyCourseInfoDto courseInfoDto = new LagouStudentStudyCourseInfoDto();
                courseInfoDto.setStudentName(stuName);
                courseInfoDto.setCourseName(courseName);

                // 过滤去重
                boolean isSaveCourseName = false;
                for (LagouStudentStudyCourseInfoDto studyCourseInfoDto : studentStudyCourseDtoList) {
                    if(studyCourseInfoDto.getCourseName().equals(courseName)){
                        isSaveCourseName = true;
                        break;
                    }
                }
                if(!isSaveCourseName){
                    studentStudyCourseDtoList.add(courseInfoDto);
                }
            }

        } catch (JSONException e) {
            log.error("com.yuer.tools.myfileziptools.service.imple.LagouStudentDetailServerImpl.parseCourse::Exception ::[{}]",e);
        }
        return  studentStudyCourseDtoList;
    }
}
